package com.you.rpc.server;

import com.you.rpc.entity.RequestCommand;
import com.you.rpc.entity.ResponseCommand;
import com.you.rpc.entity.ResponseStatus;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;


@ChannelHandler.Sharable
@Slf4j
public class ServerHandler extends SimpleChannelInboundHandler<Object> {

    private UserProcessor<Object> processors;

    public void setProcessors(UserProcessor<Object> processors) {
        this.processors = processors;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("接受请求: {} ", msg);
        if (processors != null) {
            //处理请求
            RequestCommand requestCommand = (RequestCommand) msg;
            Object requestBody = requestCommand.getRequestBody();
            //处理响应
            ResponseCommand responseCommand = new ResponseCommand();
            responseCommand.setId(requestCommand.getId());
            try {
                Object object = processors.handlerRequest(requestBody);
                responseCommand.setStatus(ResponseStatus.SUCCESS);
                responseCommand.setResponseBody(object);
            } catch (Exception e) {
                responseCommand.setStatus(ResponseStatus.ERROR);
                responseCommand.setResponseBody(null);
                e.printStackTrace();
            }
            ctx.writeAndFlush(responseCommand);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        SocketAddress address = ctx.channel().remoteAddress();
        log.info("新的连接加入:{}", address);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("连接发生异常", cause);
        ctx.close();
    }

}
